package cn.rkylin.oms.base.brand.controller;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.base.brand.dao.IBrandDAO;
import cn.rkylin.oms.base.brand.domain.Brand;
import cn.rkylin.oms.base.brand.service.IBrandService;
import cn.rkylin.oms.base.brand.vo.BrandVO;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.system.project.vo.ProjectVO;

/**
 * 类名：BrandController<br>
 * 作用：品牌信息控制类<br>
 * 创建时间：2018年1月24日 下午2:34:02
 *
 * @author LiPeng
 */
@Controller
@RequestMapping("/brand")
public class BrandController extends ApolloController {

	private static final Log logger = LogFactory.getLog(BrandController.class);
	private static final String RESULT_SUCCESS_BRAND = "success";  
	private static final String RESULT_ERROR_MESSAGE = "errormessage";
	private static final String RESULT_ROW_COUNT = "rowcount";


	private Map<String, Object> getSuccessMap(String message) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put(JSON_RESULT, SUCCESS);
		returnMap.put(JSON_MSG, message);
		return returnMap;
	};

	private Map<String, Object> getFailedMap(String message) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put(JSON_RESULT, FAILED);
		returnMap.put(JSON_MSG, message);
		return returnMap;
	};

	/**
	 * 品牌信息服务层
	 */
	@Autowired
	private IBrandService brandService;

	@ResponseBody
	@RequestMapping(value = "/getBrandList")
	public Map<String, Object> getBrandList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
			@RequestParam(required = false, defaultValue = "10") int length) throws Exception {
		logger.info("查询商品成本：/brand/getBrandList");

		BrandVO queryParamVO = new BrandVO();

		// 获取当前登录人
		CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
		if (currentUser == null) {
			return getFailedMap("查询当前登录人失败");
		}
		// 获取当前登录人所属项目
		String projectId = currentUser.getCurrentProject().getPrjId();
		if (StringUtils.isBlank(projectId)) {
			return getFailedMap("查询当前登录人所属项目失败");
		}
		String entId = null;
		// 找前台选择的项目，对应的企业（这种做法是为了适应，用户对应到多个企业下的情况。）
		for (ProjectVO project : currentUser.getProjectMap().values()) {
			if (project.getPrjId().equalsIgnoreCase(projectId)) {
				entId = project.getEntId();
			}
		}
		queryParamVO.setEntId(entId);

		// 快速查询
		if (quickSearch != null && StringUtils.isNotEmpty(quickSearch)) {
			quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
			if (StringUtils.isNotEmpty(quickSearch)) {
				queryParamVO.setQuickSearch(quickSearch.trim());
			}
		}

		Map<String, String> replaceFieldsMap = new HashMap<String, String>();
		// 排序语句生成
		String orderStatement = getOrderString(IBrandDAO.class.getName(), "pageSelectBrand", replaceFieldsMap);
		if (StringUtils.isNotEmpty(orderStatement)) {
			queryParamVO.setOrderBy(orderStatement);
		}
		// 处理分页信息
		if (length == -1) {
			length = Integer.MAX_VALUE;
		}
		int page = start / length + 1;

		// 执行查询
		PageInfo<BrandVO> brandVOList = brandService.queryBrandList(page, length, queryParamVO);

		Map<String, Object> returnMap = new HashMap<>();
		if (null != brandVOList) {
			returnMap = getSuccessMap("查询品牌信息表单数据成功");
			returnMap.put(RECORDS_FILTERED, brandVOList.getTotal());
			returnMap.put(RECORDS_TOTAL, brandVOList.getTotal());
			returnMap.put(RETURN_DATA, brandVOList.getList());
		} else {
			returnMap = getFailedMap("查询品牌信息表单数据失败");
		}
		logger.info("查询品牌信息表单数据调用结束");
		return returnMap;
	}

	/**
	 * 下载品牌信息
	 * http://localhost:8080/brand/downLoadBrand.action
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = {"/downLoadBrand"})
	public Map<String, Object> downLoadBrand() {
		Map<String, Object> rMap = new HashMap<>();
		try {
			rMap = brandService.downLoadBrand();
		} catch (Exception e) {
			rMap.put("success", "n");
			rMap.put("msg", e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return rMap;
	}

	/**
	 * 获取品牌明细信息
	 * @param brandId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/brandDetail", method = RequestMethod.GET)
	public Map<String, Object> brandDetail(String brandId) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			BrandVO brandVO = brandService.getBrandById(brandId);
			if (brandVO != null) {
				returnMap.put(JSON_RESULT, SUCCESS);
				returnMap.put(RETURN_DATA, brandVO);
			} else {
				returnMap.put(JSON_RESULT, FAILED);
				returnMap.put(RESULT_ERROR_MESSAGE, "该品牌不存在");
			}
		} catch (Exception ex) {
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(RESULT_ERROR_MESSAGE, ex.getMessage());
		}
		return returnMap;
	}

	/**
	 * 创建新品牌
	 * @param brandCode
	 * @param brandName
	 * @param entId
	 * @param remark
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/createBrand")
	public Map<String, Object> createBrand(@RequestBody BrandVO bVo)
			throws Exception {
		// 用于返回值的json对象
		Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
			returnMap.put(RESULT_ERROR_MESSAGE,"当前用户失");
			returnMap.put(RESULT_SUCCESS_BRAND,"n");
			return returnMap;
        }
		// 获取当前登录人所属项目
		String projectId = currentUser.getCurrentProject().getPrjId();
		if (StringUtils.isBlank(projectId)) {
			returnMap.put(RESULT_ERROR_MESSAGE,"查询当前登录人所属项目失败");
			returnMap.put(RESULT_SUCCESS_BRAND,"n");
			return returnMap;
		}
		String entId = null;
		String entName = null;
		// 找前台选择的项目，对应的企业（这种做法是为了适应，用户对应到多个企业下的情况。）
		for (ProjectVO project : currentUser.getProjectMap().values()) {
			if (project.getPrjId().equalsIgnoreCase(projectId)) {
				entId = project.getEntId();
				entName=project.getEntName();
			}
		}
        
		BrandVO brandVO = new BrandVO();
		brandVO.setBrandCode(bVo.getBrandCode());
		brandVO.setBrandName(bVo.getBrandName());
		brandVO.setEntId(entId);
		brandVO.setEntName(entName);
		brandVO.setUpdateTime(new Date());
		brandVO.setCreateTime(new Date());
		brandVO.setBrandId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
		brandVO.setRemark(bVo.getRemark());

		//判断编码是否存在
		Brand brand = brandService.getBrandByBrandCode(brandVO);
		if(brand!=null) {
			returnMap.put(RESULT_ERROR_MESSAGE,"该品牌编码已存在");
			returnMap.put(RESULT_SUCCESS_BRAND,"n");
			return returnMap;
		}

		//分担规则生成
		brandService.insert(brandVO);
		returnMap.put(RESULT_ROW_COUNT,1);
		returnMap.put(RESULT_SUCCESS_BRAND,"Y");
		// 生成返回结果json串，null内容也需要返回
		return returnMap;
	}

	/**
	 * 修改品牌信息
	 * @param brandID
	 * @param brandCode
	 * @param brandName
	 * @param entId
	 * @param remark
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/updateBrand")
	public Map<String, Object> updateBrand(@RequestBody BrandVO bVo) throws Exception {
		// 用于返回值的json对象
		Map<String, Object> returnMap = new HashMap<String, Object>();

		BrandVO brandVO = brandService.getBrandById(bVo.getBrandId());
		brandVO.setBrandCode(bVo.getBrandCode());
		brandVO.setBrandName(bVo.getBrandName());
		brandVO.setRemark(bVo.getRemark());
		brandVO.setUpdateTime(new Date());

		//判断编码是否存在
		Brand brand = brandService.getBrandByBrandCode(brandVO);
		if(brand!=null) {
			returnMap.put(RESULT_SUCCESS_BRAND, "n");
			returnMap.put(RESULT_ERROR_MESSAGE, "该品牌编码已存在");
			return returnMap;
		}

		//分担规则生成
		brandService.update(brandVO);
		returnMap.put(RESULT_ROW_COUNT,1);
		returnMap.put(RESULT_SUCCESS_BRAND,"Y");
		// 生成返回结果json串，null内容也需要返回
		return returnMap;
	}

	/**
	 * 删除品牌
	 * @param brandID
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteBrand")
	public Map<String, Object> deleteBrand(String brandId)
			throws Exception {
		// 用于返回值的json对象
		Map<String, Object> returnMap = new HashMap<String, Object>();

		//分担规则生成
		int result =  brandService.delete(brandId);
		returnMap.put(RESULT_ROW_COUNT,result);
		returnMap.put(RESULT_SUCCESS_BRAND,"Y");
		// 生成返回结果json串，null内容也需要返回
		return returnMap;
	}   
}
